package com.juzhencms.apps.busi.web;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.juzhencms.apps.busi.entity.AdminLoginUser;
import com.juzhencms.apps.busi.service.CommonService;
import com.juzhencms.apps.busi.service.DataHistoryService;
import com.juzhencms.apps.busi.service.DictionaryService;
import com.juzhencms.apps.busi.service.SensitiveKeywordsService;
import com.juzhencms.apps.busi.service.UserService;
import com.juzhencms.apps.base.busi.service.ConfigService;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.database.JdbcDao;
import com.juzhencms.apps.base.common.util.DataLogUtil;
import com.juzhencms.apps.common.util.ExcelExportUtil;

import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

@Data
@Slf4j
public class BaseController {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpServletResponse response;
	@Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private DictionaryService dictionaryService;
	
	@Autowired
	private DataHistoryService dataHistoryService;
	
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private ConfigService configService;
	
	@Autowired
	private DataLogUtil dataLogUtil;
	
	@Autowired
	private SensitiveKeywordsService sensitiveKeywordsService;
	
	public void logDesc(String dataType,String dataId,String description) {
		dataLogUtil.logDesc(dataType, dataId, description);
	}
	
	public void logDesc(String description) {
		dataLogUtil.logDesc(description);
	}
	
	
	public AdminLoginUser getLoginUser(){
		return userService.getLoginUser();
	}
	
	public int getLoginUserId(){
		return userService.getLoginUser().getId();
	}
	
	
	//获取当前用户管理的站点ID拼接的字符串,不包含0，用于数据查询
	/*
	public String getPermissionSiteIds() {
		Map userPermissions=this.getLoginUserPermissions();
		if(userPermissions!=null && userPermissions.get("root")==null){
			String siteIds=null;
			Map userMenu=(Map)this.getLoginUser().get("userMenu");
			if(userMenu!=null && userMenu.get("content")!=null) {
				Map contentMenu=(Map)userMenu.get("content");
				if(contentMenu!=null && contentMenu.get("sub")!=null) {
					List dataList=(List)contentMenu.get("sub");
					if(dataList!=null) {
						for(int i=0;i<dataList.size();i++) {
							Map tmpSite=(Map)dataList.get(i);
							if(siteIds==null) {
								siteIds=tmpSite.get("id").toString();
							}else {
								siteIds+=","+tmpSite.get("id").toString();
							}
							
						}
					}
				}
			}
			return siteIds;
		}else {
			return null;
		}
	}*/
	/*//获取当前用户管理的站点ID（权限下站点与机构下站点的站点ID交集）拼接的字符串，用于展示菜单或展示可推送站点
	public String getPermissionSiteIds() {
		Map userPermissions=this.getLoginUser().getPermissions();
		if(userPermissions!=null && userPermissions.get("root")==null){
			String siteIds="0";
			Map userMenu=(Map)this.getLoginUser().getUserMenu();
			if(userMenu!=null && userMenu.get("content")!=null) {
				Map contentMenu=(Map)userMenu.get("content");
				if(contentMenu!=null && contentMenu.get("sub")!=null) {
					List dataList=(List)contentMenu.get("sub");
					//获取机构下站点ID集
					String getLoginUserOrgSiteIds = this.getLoginUser().getSubOrgIds();
					if(dataList!=null && !getLoginUserOrgSiteIds.equals("") ) {
						String[] getLoginSiteIds = getLoginUserOrgSiteIds.split(",");
						for(int i=0;i<dataList.size();i++) {
							Map tmpSite=(Map)dataList.get(i);
							//求角色下的站点与机构下的站点的ID交集
							if(Arrays.asList(getLoginSiteIds).contains(tmpSite.get("id").toString())) {
								siteIds+=","+tmpSite.get("id").toString();
							}
						}
					}
				}
			}
			return siteIds;
		}else if(userPermissions.get("root")!=null){
			List siteList=this.getCommonService().getJdbcDao().querySql("select id from "+DBTable.site+" where org_id in("+this.getLoginUser().getSubOrgIds()+") and del_flag='0'");
			String siteIds=null;
			if(siteList!=null) {
				for(int i=0;i<siteList.size();i++) {
					Map tmpSite=(Map)siteList.get(i);
					if(siteIds==null) {
						siteIds=tmpSite.get("id").toString();
					}else {
						siteIds+=","+tmpSite.get("id").toString();
					}
				}
			}
			return siteIds;
		}else{
			return null;
		}
	}*/
	
	public String filterSensitiveKeywords(String table,Map data) {
		return sensitiveKeywordsService.filterSensitiveKeywords(table, data);
	}
	
	
	
	//判断登录的管理员用户是否为root管理员
	public boolean isRootUser() {
		return (boolean) userService.isRootUser();
	}
	
	String templateResult(String templateName,Map model) {
		if(model.get("contextPath")==null) {
			model.put("contextPath", request.getContextPath());
		}
		
		//如果手动调用模板输出，需要增加这个，否则会提示springMacroRequestContext不存在
		//model.put("springMacroRequestContext", new RequestContext(request, null, null, null));
		
		StringWriter stringWriter=new StringWriter();
		try {
			Template template = this.getFreeMarkerConfigurer().getConfiguration().getTemplate(templateName+".ftl");
			template.process(model, stringWriter);
			stringWriter.flush();
		} catch (TemplateNotFoundException e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage(),e);
		} catch (MalformedTemplateNameException e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage(),e);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage(),e);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage(),e);
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage(),e);
		}
		return stringWriter.toString();
	}
	
	
}
